// 实现一个 Promise.any 方法
/**
 * @template T
 * @param {(T | PromiseLike<T>)[]} promises
 * @returns {Promise<T>}
 */
export const any = (promises) => {
  if (promises.length === 0) {
    return Promise.reject(
      new AggregateError(promises, "All promises were rejected"),
    );
  }
  return new Promise((resolve, reject) => {
    let count = 0;
    for (const promise of promises) {
      if (promise instanceof Promise) {
        // eslint-disable-next-line no-loop-func
        promise.then(resolve).catch(() => {
          count++;
          if (count === promises.length) {
            reject(new AggregateError([], "All promises were rejected"));
          }
        });
      } else {
        try {
          resolve(promise);
        } catch (error) {
          reject(error);
        }
      }
    }
  });
};
